<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
      <div class="title-container">
        <div class="title">
          <img src="../../assets/images/otaLogo.png" alt="" />
          <span> 远程管理系统 </span>
        </div>
      </div>
      <el-form-item prop="username">
        <div class="svg-container">
          <!-- <svg-icon icon-class="user" /> -->
          <img src="../../assets/images/user.png" alt="" />
        </div>
        <el-input ref="username" v-model="loginForm.username" placeholder="用户名" name="username" type="text" clearable tabindex="1">
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <div class="svg-container">
          <img src="../../assets/images/pwd.png" alt="" class="pwdImg" />
        </div>
        <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType" placeholder="密码" name="password" clearable tabindex="2" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-form-item prop="captcha">
        <div class="svg-container">
          <img src="../../assets/images/yzm.png" alt="" class="pwdImg" />
        </div>
        <el-input v-model="loginForm.captcha" placeholder="验证码" type="text" clearable style="padding-right:50px" />
        <img :src="yzmImg" alt="" @click="getImg" style="cursor: pointer;">
      </el-form-item>

      <el-button :loading="loading" type="primary" class="loginBtn" style="width: 100%; margin-bottom: 30px" @click="handleLogin" @keyup.enter="handleLogin">登 录</el-button>

      <!--<div class="tips">
        <span style="margin-right:20px;">username: admin</span>
        <span> password: any</span>
      </div>-->
    </el-form>
    <!-- <div class="fotters">
      <img src="../../assets/images/xhlogo.png" alt="">
      <div class="info">内蒙古显鸿科技股份有限公司</div>
      <div>2021</div>
    </div> -->
  </div>
</template>

<script>
import { asyncRoutes, constantRoutes } from "@/router/index";

import { validUsername } from "@/utils/validate";
import * as menuApi from "@/api/sys/menu";
import { account, password } from "@/utils/validate"
import { randomImage } from "@/api/user"
import { Encrypt } from "@/utils/public"
// import base64 from "@/utils/base64"
export default {
  name: "login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入用户名"));
      } else {
        if (account(value)) {
          callback();
        } else {
          callback(new Error("用户名只能是字母或者数字"));
        }
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入密码"));
      } else {
        callback();
        // if(password(value)){
        //   callback();
        // }else{
        //   callback(new Error("请输入字母,数字或字符不少于8位的密码"));
        // }
      }
    };
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        captcha: [
          { required: true, trigger: "blur", message: '请输入验证码' },
        ]
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      yzmImg: '',
      nowTime: ''
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    var t = this;
    document.onkeydown = function (e) {
      if (window.event == undefined) {
        var key = e.keyCode;
      } else {
        var key = window.event.keyCode;
      }
      //enter的ASCII码是13
      if (key == 13) {
        t.handleLogin();
      }
    }
  },
  mounted() {
    this.getImg()
    let accountForm = localStorage.getItem('accountForm')
    if (accountForm) {
      let form = JSON.parse(accountForm)
      console.log(form);
      this.loginForm.username = form.username
      this.loginForm.password = form.password
    }
  },
  methods: {
    //获取验证码
    getImg() {
      this.nowTime = new Date().getTime()
      randomImage(this.nowTime).then(res => {
        this.yzmImg = res.message
      })
    },
    async getUserPermissionByToken(callback) {
      var p = await menuApi.getUserPermissionByToken();
      var menuList = p.data.menu;
      var btnList = p.data.auth;
      localStorage.setItem("permission_routes", JSON.stringify(menuList));
      localStorage.setItem("permission_btnList", JSON.stringify(btnList));
      var newRoutes = await this.$store.dispatch("formatRoutes", menuList);
      callback(newRoutes);
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      let t = { checkKey: this.nowTime.toString() }
      let data = Object.assign({}, t, { username: Encrypt(this.loginForm.username), password: Encrypt(this.loginForm.password), captcha: Encrypt(this.loginForm.captcha) })
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let accountForm = {
            username: this.loginForm.username,
            password: this.loginForm.password
          }
          localStorage.setItem('accountForm', JSON.stringify(accountForm))
          this.$store
            .dispatch("user/login", data)
            .then((resp) => {
              this.loading = false;
              localStorage.setItem("username", resp.username);
              this.getUserPermissionByToken((newRoutes) => {
                this.$router.push({ path: "/" });
              });
              // console.log(this.getUserPermissionByToken(), 'getUserPermissionByToken=========>');
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    // color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-form-item {
    margin-bottom: 40px;
  }
  .el-input {
    display: inline-block;
    height: 40px;
    width: 300px;

    input {
      background: #fff;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #333 !important;
      height: 40px;
      // caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: #333 !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: #fff;
    border-radius: 5px;
    color: #454545;
  }
  .el-form-item__content {
    display: flex;
    align-items: center;
  }
  .el-input__suffix {
    right: 20px !important;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  background: url("../../assets/images/bag.png") no-repeat;
  background-size: cover;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 380px;
    max-width: 100%;
    height: 450px;
    border-radius: 10px;
    background: url("../../assets/images/bgs.png") no-repeat;
    background-size: cover;
    padding: 40px 40px 0;
    margin: 10% auto 0;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    // padding: 6px 5px 6px 15px;
    // color: $dark_gray;
    display: flex;
    align-items: center;
    justify-content: center;
    vertical-align: middle;
    // width: 50px;
    margin-left: 12px;
    img {
      width: 16px;
      // height: 29px;
    }
    .pwdImg {
      width: 16px;
      // height: 29px;
    }
  }

  .title-container {
    position: relative;

    .title {
      font-family: "微软雅黑 Bold", "微软雅黑 Regular", "微软雅黑";
      font-weight: 700;
      font-style: normal;
      font-size: 24px;
      color: #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 40px;
      img {
        width: 50px;
        margin-right: 20px;
      }
    }
  }

  .show-pwd {
    position: absolute;
    right: 5px;
    top: 0;
    font-size: 15px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .loginBtn {
    height: 44px;
    line-height: 44px;
    padding: 0;
    color: #fff;
    font-size: 16px;
    .svg-icon {
      vertical-align: -0.5em !important;
    }
  }
  .fotters {
    margin-top: 12%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 16px;
    font-family: Microsoft YaHei;
    .info {
      margin: 0 32px 0 16px;
    }
  }
}
</style>
